import api from './api'
import Vuex from 'vuex'

const initStore = () => {
  const state = {
    api,
    currentStep: 0,
    upperAgentRes: {
      queriedSuc: false,
      data: {},
      queryError: false,
      message: ''
    },
    myInfo: {
      loaded: false,
      isAgentAlready: false,
      message: ''
    },
    submitRes: { data: {} },
    proxyLevel: 3
  };
  const store = new Vuex.Store({
    state,
    mutations: {
      changeUserAgentInfo(state, payload) {
        state.myInfo.loaded = true
        // state.myInfo.isAgentAlready = payload.result === 0
        state.myInfo.isAgentAlready = false
        state.myInfo.message = payload.message
      },
      changeUpperAgent(state, payload) {
        state.upperAgentRes.queriedSuc = payload.result === 0
        state.upperAgentRes.data = payload.data
        state.upperAgentRes.queryError = payload.result !== 0
        state.upperAgentRes.message = payload.message
      },
      changeSubmitRes(state, payload) {
        state.submitRes = payload
      },
      changeProxyLevel(state, payload) {
        state.proxyLevel = payload
      }
    },
    getters: {},
    actions: {
      getSelfInfo({ commit }) {
        api.homeApi.querySelf().then(res => res.json()).then(data => {
          console.log('myinfo', data)
          commit('changeUserAgentInfo', data)
        })
      },
      queryUpper({ commit }, payload) {
        return api.homeApi.queryUpperAgent(payload).then(res => res.json()).then(data => {
          console.log(data);
          commit('changeUpperAgent', data)
        })
      },
      submitInfo({ commit }, payload) {
        api.homeApi.apply(payload).then(res => res.json()).then(data => {
          commit('changeSubmitRes', {
            applying: false,
            resData: data
          })
        })
      }
    }
  });

  return store;
};

export default initStore;